﻿using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Xml.Linq;
using Unread.Business.Data.Opml.Interfaces;
using Unread.Business.Data.Opml.Model;

namespace Unread.Business.Data.Opml
{
    [Export(typeof(IOpmlWriter))]
    internal class OpmlWriter : IOpmlWriter
    {
        public string Write(Root opml)
        {
            if (opml == null) throw new ArgumentNullException("opml");

            var xml = new XDocument();

            var root = new XElement("opml", new XAttribute("version", "1.0"));
            xml.Add(root);

            var head = new XElement("head");
            root.Add(head);

            var headTitle = new XElement("title", opml.Head.Title);
            head.Add(headTitle);

            var body = new XElement("body");
            root.Add(body);

            var outlines = from outline in opml.Body.Outlines
                           select new XElement("outline",
                               new XAttribute("id", outline.Id.ToString()),
                               new XAttribute("title", outline.Title ?? string.Empty),
                               new XAttribute("text", outline.Subtitle ?? string.Empty),
                               new XAttribute("type", outline.Type ?? string.Empty),
                               new XAttribute("xmlUrl", outline.XmlUrl.AbsoluteUri),
                               new XAttribute("htmlUrl", (outline.HtmlUrl != null ? outline.HtmlUrl.AbsoluteUri : string.Empty)),
                               new XAttribute("subtitle", outline.Subtitle ?? string.Empty),
                               new XAttribute("image", (outline.Image != null ? outline.Image.AbsoluteUri : string.Empty)),
                               new XAttribute("lastRead", outline.LastRead.Ticks));
            body.Add(outlines);

            return xml.ToString();
        }
    }
}